﻿using Common.Result;
using log4net.Config;
using log4net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Service;
using WebApi.Controllers;

namespace WebApi.Filter
{
    public class CustomerExceptionFilter : IAsyncExceptionFilter
    {
        private readonly ILog _log;

        public CustomerExceptionFilter()
        {
            // 获取ILog对象
            _log = LogManager.GetLogger(typeof(CustomerExceptionFilter));
        }
        public Task OnExceptionAsync(ExceptionContext context)
        {
            //将异常输出至日志
            _log.Error(context.Exception.Message);
            //如果异常没有被处理则进行处理
            if (context.ExceptionHandled == false) {
                var result = ResultHelper.Error("服务器繁忙，请稍后再试");
                context.Result = new ContentResult
                {
                    StatusCode = StatusCodes.Status200OK,
                    ContentType = "application/json;charset=utf-8",
                    Content = JsonConvert.SerializeObject(result)
                };
            }
            //表示异常已被处理
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}
